package org.ssp.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.security.KeyPair;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.ssp.base.GetRandomInt;
import org.ssp.dao.AssistDao;
import org.ssp.dao.UserDao;
import org.ssp.impl.AssistImpl;
import org.ssp.impl.UserImpl;
import org.ssp.pojo.Assister;
import org.ssp.pojo.User;
import org.ssp.service.CoreService;
import org.ssp.util.CommonUtil;
import org.ssp.util.JCryptionUtil;
import org.ssp.util.SmsUtil;

import net.sf.json.JSONObject;



/**
 * 
 * 手机页面登录或者微信账号绑定登录
 * 
 * @author susp
 *
 */

@WebServlet("/login")
public class LogInServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String method=request.getParameter("method");
		if(method!=null){
			String state=request.getParameter("state");//判断是微信客户端授权登录还是网页授权登录
			String openid=null;
			String access_token=null;
			if("wxpage".equals(method)){//判断是否绑定，已经绑定过跳转success,未绑定跳转wxlogin
				String code=request.getParameter("code");	
				System.out.println("wxpage:"+code);
				//获取openid
				if(code!=null){
					//通过code换取access_token
					String urlApi="https://api.weixin.qq.com/sns/oauth2/access_token?appid=wxf34da76143f5050d&secret=7a6df503a9afaa70601d652cfb99b16d&code=CODE&grant_type=authorization_code";
					String url=urlApi.replace("CODE", code);
					try {
						String str=CommonUtil.httpsRequest(url, "POST", null);
						JSONObject json=JSONObject.fromObject(str);
						if(null!=json){
							access_token=(String) json.getString("access_token");
							openid=(String) json.getString("openid");
							System.out.println("openid..."+openid);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
			    }
			    UserDao userdao=new UserImpl();
			    if(userdao.findByOpenId(openid)==null){
			    	request.setAttribute("openid", openid);
					request.getRequestDispatcher("/WEB-INF/page/user/wxlogin.jsp").forward(request, response);
			    }else{
			    	request.setAttribute("key", "1");
			    	request.getRequestDispatcher("/WEB-INF/page/user/bindsuccess.jsp?key=1").forward(request, response);
			    }
			}else if("urllogin".equals(method)){//绑定openid到账户
			    String phone=request.getParameter("phone1");
				openid=request.getParameter("openid");	
				System.out.println("urllgin..."+openid);
				//1.还未创建账户，创建用户，然后绑定     2，已经存在账户，绑定openid到账户
			    UserDao userdao=new UserImpl();
			    User user=userdao.findByPhone(phone);
			    if(user==null){//不存在，先用phone注册,自动生成uid：xxxx@phone;
					user=new User();
			    	user.setPhone(phone);
			    	user.setUid(phone+"@phone");
			    	userdao.addUser(user);//注册账户
			    }
			/*	//通过acccess_token和OpenID获取到微信用户个人信息
				String urlapi2="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
				System.out.println("access_token.........."+access_token);
				String url2=urlapi2.replace("ACCESS_TOKEN", access_token).replace("OPENID", openid);
				try {
					String str2=CommonUtil.httpsRequest(url2, "GET", null);
					System.out.println(str2);
					JSONParser parser = new JSONParser();  
					JSONObject json = (JSONObject) parser.parse(str2);
					if(null!=json){
						System.out.println("用户信息"+str2);
					}
			
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}*/
			    //绑定opendid到账户
			    user.setOpenid(openid);
			    userdao.update(user);
			    request.setAttribute("key", "2");
			    request.getRequestDispatcher("/WEB-INF/page/user/bindsuccess.jsp").forward(request, response);
			}else if("modallogin".equals(method)){
				System.out.println("modallogin..............");	
				 openid=request.getParameter("openid");	
                 String phone=request.getParameter("phone");
				 String checkcode=request.getParameter("code");
				 System.out.println("openid"+openid);
				 System.out.println("code"+checkcode);
				 System.out.println("phone"+phone);
				 
			     JSONObject json = new JSONObject();
			     if(checkcode.equals(request.getSession().getAttribute("code4"))){
					//1.还未创建账户，创建用户，然后绑定     2，已经存在账户，绑定openid到账户
				    UserDao userdao=new UserImpl();
				    User user=userdao.findByPhone(phone);
				    if(user==null){//不存在，先用phone注册,自动生成uid：xxxx@phone;
						user=new User();
				    	user.setPhone(phone);
				    	user.setUid(phone+"@phone");
				    	userdao.addUser(user);//注册账户
				    }
				    user.setOpenid(openid);
				    userdao.update(user);
				    json.element("flag", "1");
			     }else {
			    	 System.out.println("0............");
			    	 json.put("flag", "0");
			    	 json.put("msg", "验证码错误，重新输入");
			    	
			     }
				response.setContentType("application/x-json;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(json.toString());
			    return;
			}else if("sendcode".equals(method)){//发送手机验证码
				   String phone=request.getParameter("mobile");
				   System.out.println(phone);
				  //生成随机4位验证码，保存session
				   String code4= GetRandomInt.getRandomString(4);
				   request.getSession().setAttribute("code4", code4);
				   //发送短信验证码
				   String testUsername = "Goodsu"; //在短信宝注册的用户名
			       String testPassword = "ssp08294112"; //在短信宝注册的密码
			       String testPhone = phone;
			         // 注意测试时，也请带上公司简称或网站签名，发送正规内容短信。千万不要发送无意义的内容：例如 测一下、您好。否则可能会收不到
			       String testContent = "【廣州歐星留學】您的验证码是"+code4;
			       String httpUrl = "http://api.smsbao.com/sms";
			       SmsUtil.sendMessage(httpUrl, testUsername,testPassword,testPhone,testContent);
			       return;
				
			}else if("check1".equals(method)){//用phone和验证码登录，校验

			     String phone=request.getParameter("mobile");
				 String checkcode=request.getParameter("code");
			     UserDao userd=new UserImpl();
			     JSONObject json = new JSONObject();
			     if(userd.findByPhone(phone)!=null&&checkcode.equals(request.getSession().getAttribute("code4"))){
			    	 System.out.println("....1");
			    	 json.put("ok", 1);
			     }else {
			    	 System.out.println("phone"+phone);
			    	 if(userd.findByPhone(phone)==null){
			    		 System.out.println("....2");

				    	json.element("ok2", 2);
				    	json.element("msg2", "还未注册，请先注册");
				     }
			    	 if(!checkcode.equals(request.getSession().getAttribute("code4"))){
				    	 System.out.println("....3");

				    	 json.element("ok3", 3);
						 json.element("msg3", "验证码错误，重新输入");
				     }
			     }
				response.setContentType("application/x-json;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(json.toString());
			    return;
			}else if("check2".equals(method)){//用phone和密码方式登录，校验
				 String phone=request.getParameter("mobile");
				 String pwd=request.getParameter("pass");
				  //rsa解密
				   KeyPair keys = (KeyPair) request.getSession().getAttribute("keys1");
				   String decryptedPwd=null;
					try {
						decryptedPwd = JCryptionUtil.decrypt(pwd, keys);
						System.out.println(decryptedPwd);

					} catch (Exception e) {
						e.printStackTrace();
					}
				 UserDao userd=new UserImpl();
			     JSONObject json = new JSONObject();
			     if(userd.findByphonepwd(phone, decryptedPwd)!=null){
			    	 json.element("ok", 1);
			     }else{
			    	 json.element("msg", "手机号或密码不正确");
			     }
			 	response.setContentType("application/x-json;charset=utf-8");
				PrintWriter out=response.getWriter();
				out.write(json.toString());
			    return;
			     
			}else if("checkcode".equals(method)){//绑定时的校验
					 String checkcode=request.getParameter("code");
				     JSONObject json = new JSONObject();
				     if(checkcode.equals(request.getSession().getAttribute("code4"))){
				    	 json.element("ok", 1);
				     }else {
				    	 json.element("msg", "验证码错误，重新输入");
				     }
					response.setContentType("application/x-json;charset=utf-8");
					PrintWriter out=response.getWriter();
					out.write(json.toString());
				    return;
			     
			}else if("login".equals(method)){ //直接跳转到个人中心
		      request.getSession().setAttribute("user", null);
		      request.getRequestDispatcher("/WEB-INF/page/user/usercenter.jsp").forward(request, response);
			}//后台登录
			else if("check".equals(method)){//后台登录请求
				System.out.println("check...........");
				String id=request.getParameter("id");
				String pwd=request.getParameter("pwd");
				Assister assist=new Assister();
				//检查assist是否存在
				AssistDao assistd=new AssistImpl();
				assist=assistd.findAssist(id, pwd);
				JSONObject json=new JSONObject();
				if(assist!=null){
					System.out.println("....///....");
					json.element("success", true);
					request.getSession().setAttribute("assist", assist);
				}else{
					json.element("success",false);
				}
				PrintWriter out=response.getWriter();
				out.write(json.toString());
				return;
			}else if("admin".equals(method)){
				//保存asssit信息到session
				System.out.println("admin.....");
				Assister assist=(Assister)request.getSession().getAttribute("assist");
				System.out.println(assist.getId());
				request.getRequestDispatcher("/WEB-INF/page/admin/dashboard.jsp").forward(request, response);
			}else if("login-wx".equals(method)){//自动创建用户并绑定openid。点击1）个人中心；2）近期活动
				System.out.println("login......login-wx.....");
				String code=request.getParameter("code");	
				UserDao ud=new UserImpl();
				//获取openid
				if(code!=null){
					//通过code换取access_token
					String urlApi="https://api.weixin.qq.com/sns/oauth2/access_token?appid="+CoreService.AppID+"&secret="+CoreService.AppSecret+"&code=CODE&grant_type=authorization_code";
					String url=urlApi.replace("CODE", code);
					try {
						String str=CommonUtil.httpsRequest(url, "POST", null);
						JSONObject json=JSONObject.fromObject(str);
						if(null!=json){
							access_token=(String) json.getString("access_token");
							openid=(String) json.getString("openid");
							System.out.println("openid..."+openid);
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
			    }
				User user=ud.findByOpenId(openid);
				if(user!=null){//如果已经绑定过，直接返回
					JSONObject jsonout=new JSONObject();
			    	jsonout.element("user", user);
			    	PrintWriter out=response.getWriter();
					out.write(jsonout.toString());
					return;
				}else{
			    //通过acccess_token和OpenID获取到微信用户个人信息
				String urlapi2="https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
				System.out.println("access_token.........."+access_token);
				String url2=urlapi2.replace("ACCESS_TOKEN", access_token).replace("OPENID", CoreService.AppID);
				JSONObject json=null;
				try {
					String str2=CommonUtil.httpsRequest(url2, "GET", null);
					System.out.println(str2);
					json=JSONObject.fromObject(str2); 
					if(null!=json){
						System.out.println("用户信息"+json.getString("openid"));
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		    	String uid=UUID.randomUUID().toString();
		    	user=new User();
				user.setImg(json.getString("headimgurl"));
		    	user.setUid(uid);
		        user.setOpenid(json.getString("openid"));
		        user.setNickname(json.getString("nickname"));
		        user.setAddress(json.getString("province")+json.getString("city"));
		        user.setType(0);
		    	ud.addUser3(user);//注册账户
		    	JSONObject jsonout=new JSONObject();
		    	jsonout.element("user", user);
		    	PrintWriter out=response.getWriter();
				out.write(jsonout.toString());
				return;
				}
			}
		}else{//手机端请求login.jsp页面
			 try { 
			   //创建keypair
				JCryptionUtil jcryption=new JCryptionUtil();
				KeyPair keys=null;
				keys=jcryption.generateKeypair(512);
				//保存秘钥到session
				request.getSession().setAttribute("keys1", keys);
				String e=JCryptionUtil.getPublicKeyModulus(keys);
				String n=JCryptionUtil.getPublicKeyExponent(keys);
				String md=String.valueOf(JCryptionUtil.getMaxDigits(512));
				//同时将公钥返回给前台用于密码加密传输
			    request.setAttribute("publickey", e);
			    request.setAttribute("exponent", n);
			    request.setAttribute("maxdigit", md);
				} catch (Exception e) {
					e.printStackTrace();
			 }
		   request.getRequestDispatcher("/WEB-INF/page/user/login.jsp").forward(request, response);
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
